/*
 * Copyright 2012 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.android.apps.mytracks.investigados;

import com.doverty.android.maps.mytracks.R;
import com.google.android.apps.mytracks.AbstractMyTracksActivity;
import com.google.android.apps.mytracks.content.Investigado;
import com.google.android.apps.mytracks.content.TelefonoInvestigado;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.util.IntentUtils;
import com.google.android.apps.mytracks.util.TrackRecordingServiceConnectionUtils;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

/**
 * An activity to add/edit a investigado.
 *
 * @author Jimmy Shih
 */
public class InvestigadoEditActivity extends AbstractMyTracksActivity {

  private static final String TAG = InvestigadoEditActivity.class.getSimpleName();

  public static final String EXTRA_TRACK_ID = "track_id";
  public static final String EXTRA_INVESTIGADO_ID = "investigado_id";

  private long trackId;
  private long investigadoId;
  private boolean newInvestigado;
  private TrackRecordingServiceConnection trackRecordingServiceConnection;
  private Investigado investigado;
  private List<TelefonoInvestigado> telefonosInvestigado;
  private TelefonoInvestigadoDataSource dbTelefonoInvestigado;
  private InvestigadoDataSource dbInvestigado;


  // UI elements
  private EditText investigadoNombre;
  private TextView investigadoTelefono1;
  private Spinner investigadoTelefonoTipo1;
  private ArrayAdapter<CharSequence> myAdap;
  private TextView nuevoTelefono1;
  private TextView investigadoTelefono2;
  private Spinner investigadoTelefonoTipo2;
  private TextView nuevoTelefono2;
  private TextView investigadoTelefono3;
  private Spinner investigadoTelefonoTipo3;
  private EditText investigadoDireccion;
  private EditText investigadoEmail;

  private Button done;

  @Override
  protected void onCreate(Bundle bundle) {
    
    super.onCreate(bundle);
    trackId = getIntent().getLongExtra(EXTRA_TRACK_ID, -1L);
    investigadoId = getIntent().getLongExtra(EXTRA_INVESTIGADO_ID, -1L);
    newInvestigado = investigadoId == -1L;
    trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, null);
    myAdap = ArrayAdapter.createFromResource(this, R.array.tipos_telefono,android.R.layout.simple_spinner_item);
    getupUIElements();
    setupUIElements();
    updateUiByinvestigadoId();
  }

  private void getupUIElements() {
    
    investigadoNombre = (EditText) findViewById(R.id.investigado_edit_name);
    investigadoTelefono1 = (EditText) findViewById(R.id.investigado_edit_telefono_num1);
    investigadoTelefonoTipo1 = (Spinner) findViewById(R.id.investigado_edit_telefono_tipo1);
    nuevoTelefono1 = (TextView) findViewById(R.id.investigado_edit_telefono_nuevo1);
    investigadoTelefono2 = (EditText) findViewById(R.id.investigado_edit_telefono_num2);
    investigadoTelefonoTipo2 = (Spinner) findViewById(R.id.investigado_edit_telefono_tipo2);
    nuevoTelefono2 = (TextView) findViewById(R.id.investigado_edit_telefono_nuevo2);
    investigadoTelefono3 = (EditText) findViewById(R.id.investigado_edit_telefono_num3);
    investigadoTelefonoTipo3 = (Spinner) findViewById(R.id.investigado_edit_telefono_tipo3);
    investigadoDireccion = (EditText) findViewById(R.id.investigado_edit_direccion);
    investigadoEmail = (EditText) findViewById(R.id.investigado_edit_email);
    Button cancel = (Button) findViewById(R.id.investigado_edit_cancel);
    cancel.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        finish();
      }
    });
    done = (Button) findViewById(R.id.investigado_edit_done);
    done.setText(newInvestigado ? R.string.generic_add : R.string.generic_save);
  }

  private void setupUIElements() {


    investigadoTelefono1.addTextChangedListener(new TextWatcher() {

      @Override
      public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (start+count>0)
          nuevoTelefono1.setVisibility(View.VISIBLE);
        else
          nuevoTelefono1.setVisibility(View.GONE);
      }
   });
    
    investigadoTelefono2.addTextChangedListener(new TextWatcher() {

      @Override
      public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // TODO Auto-generated method stub
        
      }

      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (start+count>0)
          nuevoTelefono2.setVisibility(View.VISIBLE);
        else
          nuevoTelefono2.setVisibility(View.GONE);
      }
   });

    nuevoTelefono1.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        nuevoTelefono1.setVisibility(View.GONE);
        findViewById(R.id.investigado_detail_telefono_info2).setVisibility(View.VISIBLE);
        investigadoTelefonoTipo2.setAdapter(myAdap);
        investigadoTelefonoTipo2.setSelection(0);

      }
    });
    
    nuevoTelefono2.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        nuevoTelefono2.setVisibility(View.GONE);
        findViewById(R.id.investigado_detail_telefono_info3).setVisibility(View.VISIBLE);
        investigadoTelefonoTipo3.setAdapter(myAdap);
        investigadoTelefonoTipo3.setSelection(0);
     }
    });
  }



  @Override
  protected void onStart() {
    super.onStart();
    TrackRecordingServiceConnectionUtils.startConnection(this, trackRecordingServiceConnection);
  }
  
  @Override
  protected void onStop() {
    super.onStop();
    trackRecordingServiceConnection.unbind();
  }

  @Override
  protected int getLayoutResId() {
    return R.layout.investigado_edit;
  }

  /**
   * Updates the UI based on the investigado id.
   */
  private void updateUiByinvestigadoId() {
  
    setTitle(newInvestigado ? R.string.menu_insert_investigado : R.string.menu_edit);
    done.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (!investigadoNombre.getText().toString().equals("")){
          if (newInvestigado) {
            addinvestigado();
          } else {
            updateInvestigado();
          }
          Intent intent = IntentUtils.newIntent(InvestigadoEditActivity.this, InvestigadosListActivity.class);
          finish();
          startActivity(intent);
        }
        else{
          Toast.makeText(getApplicationContext(), R.string.investigado_add_error_empty_name, Toast.LENGTH_SHORT).show();
        }
      }
    });
  
    if (newInvestigado) {
      investigadoNombre.selectAll();
      investigadoTelefonoTipo1.setAdapter(myAdap);
    } 
    else {
      dbInvestigado = new InvestigadoDataSource(this);
      dbInvestigado.open();
      investigado =  dbInvestigado.getInvestigado(investigadoId);
      if (investigado == null) {
        Log.d(TAG, "investigado is null");
        finish();
        return;
      }
      else{
        investigadoNombre.setText(investigado.getNombre());
        rellenarTelefonos();
        investigadoDireccion.setText(investigado.getDireccion());
        investigadoEmail.setText(investigado.getEmail());
      }
    }
  }

  private void rellenarTelefonos() {
    
    investigadoTelefonoTipo1.setAdapter(myAdap);
    dbTelefonoInvestigado = new TelefonoInvestigadoDataSource(this);
    dbTelefonoInvestigado.open();
    telefonosInvestigado = dbTelefonoInvestigado.getAllTelefonoInvestigado(investigadoId);
    if (telefonosInvestigado.size()>0){
      investigadoTelefono1.setText(telefonosInvestigado.get(0).getNumero());
      int spinnerPosition = myAdap.getPosition(telefonosInvestigado.get(0).getTipo());
      investigadoTelefonoTipo1.setSelection(spinnerPosition);
      if (telefonosInvestigado.size()>1){
        investigadoTelefonoTipo2.setAdapter(myAdap);
        investigadoTelefono2.setText(telefonosInvestigado.get(1).getNumero());
        spinnerPosition = myAdap.getPosition(telefonosInvestigado.get(1).getTipo());
        investigadoTelefonoTipo2.setSelection(spinnerPosition);
        findViewById(R.id.investigado_detail_telefono_info2).setVisibility(View.VISIBLE);
        nuevoTelefono1.setVisibility(View.GONE);
        if (telefonosInvestigado.size()>2){
          investigadoTelefonoTipo3.setAdapter(myAdap);
          investigadoTelefono3.setText(telefonosInvestigado.get(2).getNumero());
          spinnerPosition = myAdap.getPosition(telefonosInvestigado.get(2).getTipo());
          investigadoTelefonoTipo3.setSelection(spinnerPosition);
          findViewById(R.id.investigado_detail_telefono_info3).setVisibility(View.VISIBLE);
          nuevoTelefono2.setVisibility(View.GONE);
        }
      }
    }
  }
  
  /**
   * Adds a client.
   */
  private void addinvestigado() {
    
    dbInvestigado = new InvestigadoDataSource(this);
    dbInvestigado.open();
    dbTelefonoInvestigado = new TelefonoInvestigadoDataSource(this);
    dbTelefonoInvestigado.open();
    Investigado investigadoCreation = new Investigado(
        investigadoNombre.getText().toString(),
        investigadoDireccion.getText().toString(), investigadoEmail.getText().toString());
    long insertInvestigadoId = dbInvestigado.createInvestigado(investigadoCreation);
    
    if (!(investigadoTelefono1.getText().toString().equals(""))){
      TelefonoInvestigado telefonoInvestigadoCreation = new TelefonoInvestigado(insertInvestigadoId,
      investigadoTelefono1.getText().toString(),
      investigadoTelefonoTipo1.getSelectedItem().toString());
      dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation);
    }

    if (!(investigadoTelefono2.getText().toString().equals(""))){
      TelefonoInvestigado telefonoInvestigadoCreation2 = new TelefonoInvestigado(insertInvestigadoId,
      investigadoTelefono2.getText().toString(),
      investigadoTelefonoTipo2.getSelectedItem().toString());
      dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation2);
      }
    
    if (!(investigadoTelefono3.getText().toString().equals(""))){
      TelefonoInvestigado telefonoInvestigadoCreation3 = new TelefonoInvestigado(insertInvestigadoId,
      investigadoTelefono3.getText().toString(),
      investigadoTelefonoTipo3.getSelectedItem().toString());
      dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation3);
      }
    Toast.makeText(this, R.string.investigado_add_success, Toast.LENGTH_SHORT).show();
  }

  /**
   * update a investigado.
   */
  private void updateInvestigado() {
    Investigado investigadoCreation = new Investigado(investigadoId,
        investigadoNombre.getText().toString(),
        investigadoDireccion.getText().toString(), investigadoEmail.getText().toString());
    dbInvestigado.updateInvestigado(investigadoCreation);
    updateTelefonos();
  }
  
  private void updateTelefonos(){
    
    if (telefonosInvestigado.size()>0){
      if((telefonosInvestigado.get(0).getNumero()!=investigadoTelefono1.getText().toString() || 
          telefonosInvestigado.get(0).getTipo()!=investigadoTelefonoTipo1.getSelectedItem().toString())){
        TelefonoInvestigado telefonoInvestigadoCreation = new TelefonoInvestigado(telefonosInvestigado.get(0).getId(),
            investigadoId,investigadoTelefono1.getText().toString(), investigadoTelefonoTipo1.getSelectedItem().toString());
        dbTelefonoInvestigado.updateTelefonoInvestigado(telefonoInvestigadoCreation);
      }
      if (telefonosInvestigado.size()>1){
        if((telefonosInvestigado.get(1).getNumero()!=investigadoTelefono2.getText().toString() || 
            telefonosInvestigado.get(1).getTipo()!=investigadoTelefonoTipo2.getSelectedItem().toString())){
          TelefonoInvestigado telefonoInvestigadoCreation = new TelefonoInvestigado(telefonosInvestigado.get(1).getId(),
              investigadoId,investigadoTelefono2.getText().toString(), investigadoTelefonoTipo2.getSelectedItem().toString());
          dbTelefonoInvestigado.updateTelefonoInvestigado(telefonoInvestigadoCreation);
        }
        if (telefonosInvestigado.size()>2){
          if((telefonosInvestigado.get(2).getNumero()!=investigadoTelefono3.getText().toString() || 
              telefonosInvestigado.get(2).getTipo()!=investigadoTelefonoTipo3.getSelectedItem().toString())){
            TelefonoInvestigado telefonoInvestigadoCreation = new TelefonoInvestigado(telefonosInvestigado.get(2).getId(),
                investigadoId,investigadoTelefono3.getText().toString(), investigadoTelefonoTipo3.getSelectedItem().toString());
            dbTelefonoInvestigado.updateTelefonoInvestigado(telefonoInvestigadoCreation);
          }
        }
        else{
          if (!(investigadoTelefono3.getText().toString().equals(""))){
            TelefonoInvestigado telefonoInvestigadoCreation2 = new TelefonoInvestigado(investigadoId,
            investigadoTelefono3.getText().toString(),
            investigadoTelefonoTipo3.getSelectedItem().toString());
            dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation2);
            }
        }
      }
      else{
        if (!(investigadoTelefono2.getText().toString().equals(""))){
          TelefonoInvestigado telefonoInvestigadoCreation2 = new TelefonoInvestigado(investigadoId,
          investigadoTelefono2.getText().toString(),
          investigadoTelefonoTipo2.getSelectedItem().toString());
          dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation2);
        }
      }
    }
    else{
      if (!(investigadoTelefono1.getText().toString().equals(""))){
        TelefonoInvestigado telefonoInvestigadoCreation = new TelefonoInvestigado(investigadoId,
        investigadoTelefono1.getText().toString(),
        investigadoTelefonoTipo1.getSelectedItem().toString());
        dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation);
      }

      if (!(investigadoTelefono2.getText().toString().equals(""))){
        TelefonoInvestigado telefonoInvestigadoCreation2 = new TelefonoInvestigado(investigadoId,
        investigadoTelefono2.getText().toString(),
        investigadoTelefonoTipo2.getSelectedItem().toString());
        dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation2);
      }
      
      if (!(investigadoTelefono3.getText().toString().equals(""))){
        TelefonoInvestigado telefonoInvestigadoCreation3 = new TelefonoInvestigado(investigadoId,
        investigadoTelefono3.getText().toString(),
        investigadoTelefonoTipo3.getSelectedItem().toString());
        dbTelefonoInvestigado.createTelefonoInvestigado(telefonoInvestigadoCreation3);
      }
    }
  }
}
